package com.abe.libquick.utils.download;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;

import com.abe.libcore.base.permission.PermissionUtils;
import com.abe.libcore.utils.CommonUtils;
import com.abe.libcore.utils.ExternalFileUtils;
import com.abe.libcore.utils.FileDownloadUtils;
import com.abe.libquick.utils.quick.ToastTool;

import java.io.File;
import java.util.Locale;

public class DownloadDataManager {
    private Context mContext;
    private String folderFullPath;
    /* 随机生成文件名 */
    private String apkName;
    /* 下载地址 */
    private String apkUrl;
    private long downloadId;

    /**
     * @param folderName 相对路径在mcdull/file底下
     */
    public DownloadDataManager(Context context, String apkUrl, String folderName, String versionName) {
        this.mContext = context;
        String path = ExternalFileUtils.INSTANCE.fileRootPath();
        this.folderFullPath = TextUtils.isEmpty(folderName) ? path : path + File.separator + folderName;
        this.apkUrl = apkUrl;
        apkName = String.format(Locale.CHINA, "%s.apk", versionName);
        mContext.registerReceiver(new DownloadCompleteReceiver(), new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        if (isFolderExists()) {
            downloadApk();
        } else {
            ToastTool.show("下载失败，路径不存在");
        }
    }

    public DownloadDataManager(Context context, String apkUrl, String versionName) {
        this(context, apkUrl, "", versionName);
    }

    private boolean isFolderExists() {
        File file = new File(folderFullPath);
        return file.exists() || file.mkdirs();
    }

    private void downloadApk() {
        DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request down = new DownloadManager.Request(Uri.parse(apkUrl));
        //下载中和下载完后都显示通知栏
        down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        //通知栏标题
        down.setTitle("下载");
        //通知栏描述信息
        down.setDescription("更新包下载");
        // 设置允许使用的网络类型，这里是移动网络和wifi都可以
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        // 禁止发出通知，既后台下载
        // down.setShowRunningNotification(false);
        //设置类型为.apk
        down.setMimeType("application/vnd.android.package-archive");
        // 不显示下载界面
        down.setVisibleInDownloadsUi(true);
        // 设置下载后文件存放的位置
        down.setDestinationInExternalFilesDir(mContext, null, apkName);
        down.setDestinationUri(Uri.fromFile(new File(folderFullPath + File.separator + apkName)));
        // 将下载请求放入队列
        if (manager != null)
            downloadId = manager.enqueue(down);
        CommonUtils.INSTANCE.log("DownloadManager-downloadId:" + downloadId);
    }

    //安装APK文件
    private void installApk() {
        File apkFile = new File(folderFullPath, apkName);
        if (!apkFile.exists()) {
            return;
        }
        PermissionUtils.INSTANCE.installApk(mContext, apkFile);
    }

    private void checkStatus(Context context, long id) {
        DownloadManager.Query query = new DownloadManager.Query();
        DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        query.setFilterById(id);
        Cursor c = dm.query(query);
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    int status = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
                    switch (status) {
                        //下载暂停
                        case DownloadManager.STATUS_PAUSED:
                            break;
                        //下载延迟
                        case DownloadManager.STATUS_PENDING:
                            break;
                        //正在下载
                        case DownloadManager.STATUS_RUNNING:
                            break;
                        //下载完成
                        case DownloadManager.STATUS_SUCCESSFUL:
                            ToastTool.show("下载完成");
                            installApk();
                            break;
                        //下载失败
                        case DownloadManager.STATUS_FAILED:
                            String filePath = folderFullPath + File.separator + apkName;
                            FileDownloadUtils.get().download(apkUrl, filePath, folderFullPath,
                                    new FileDownloadUtils.OnDownloadListener() {
                                        @Override
                                        public void onDownloadSuccess(String filePath) {
                                            installApk();
                                        }

                                        @Override
                                        public void onDownloading(int progress) {

                                        }

                                        @Override
                                        public void onDownloadFailed(String error) {
                                            ToastTool.show("下载失败，请联系管理员");
                                        }
                                    });
                            break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                c.close();
            }
        }
    }

    // 接受下载完成后的intent
    class DownloadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action != null && action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                //在广播中取出下载任务的id
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (id == downloadId) {
                    checkStatus(context, id);
                }
            }
        }
    }
}